﻿using System.Collections.Generic;
using System.Reflection;
using System.Text;
using smp.QueryDb.Structure;

namespace smp.QueryDb
{
    internal class Sort
    {
        private readonly PropertyInfo _property;
        private Column _column;
        private readonly bool _isDescending;
        private string _declaration;

        internal Sort(PropertyInfo property, bool isDescending)
        {
            _property = property;
            _isDescending = isDescending;
        }

        internal Sort(Column column, bool isDescending)
        {
            _column = column;
            _isDescending = isDescending;
            _declaration = isDescending
                              ? string.Format("{0} DESC", column.Declaration)
                              : column.Declaration;
        }

        internal void AppendStatementBuilder(List<Map> maps,  StringBuilder statement, Table table)
        {
            if(_column == null)
            {
                if(_property == null)
                    return;

                var mapColumn = Helper.GetMapColumn(_property, maps);
                if(mapColumn == null)
                {
                    throw Helper.Error("Invalid order by property : {0}, you must supply a map to the column", 
                        _property.Name);
                }
                _column = mapColumn;
            }

            if(!table.IsTableDeclared(_column.TableDeclaration))
            {
                throw Helper.Error("Invalid order by column : {0}, table declaration {1} is not defined in from call.",
                             _column.Name,
                             _column.TableDeclaration);
            }

            statement.AppendFormat(_isDescending ? " {0} DESC," : "{0},", _column.Declaration);
        }
    }
}
